#include "dominion.h"
#include "dominion_helpers.h"
#include <stdlib.h>

int ops_hand_counts(int player, struct gameState *state)
{
    int i;
    int res = 0;

    for(i = 0; i < state->numPlayers; i++)
        if(i != player) {
            res += state->handCount[i];
        }

    return res;
}

void fill_array(int *s, int v, size_t n)
{
    while(n--)
        s[n] = v;
}

int ops_deck_counts(int player, struct gameState *state)
{
    int i;
    int res = 0;

    for(i = 0; i < state->numPlayers; i++)
        if(i != player) {
            res += state->deckCount[i];
        }

    return res;
}

int ops_discard_counts(int player, struct gameState *state)
{
    int i;
    int res = 0;

    for(i = 0; i < state->numPlayers; i++)
        if(i != player) {
            res += state->handCount[i];
        }

    return res;
}

void replace_card(int player, struct gameState *state, int from, int to)
{
    int i;

    for(i = 0; i < state->handCount[player]; i++)
        if(state->hand[player][i] == from)
            state->hand[player][i] = to;
}

int count_in_hand(int player, struct gameState *state, int card)
{
    int i;
    int res = 0;

    for(i= 0; i < state->handCount[player]; i++)
        if(state->hand[player][i] == card) {
            res++;
        }

    return res;
}

int randRange(int lhs, int rhs)
{
    int min, max;
    if(lhs < rhs) {
        min = lhs;
        max = rhs;
    } else {
        min = rhs;
        max = lhs;
    }

    return min + (rand() % ((max - min) + 1));
}

int randCard(void)
{
    return randRange(curse, treasure_map);
}

int numersort(const void *lhs, const void *rhs)
{
    const int *a = (int *)(lhs);
    const int *b = (int *)(rhs);

    return (*a > *b) - (*a < *b);
}

int compare_cards(int *to, int to_count, int *from, int from_count)
{
    int *sm, *lg;
    int sm_count, lg_count;
    int lim;
    int same = 0;
    int sm_index, lg_index;

    // Sort the arrays for faster comparison
    qsort(to, to_count, sizeof(int), numersort);
    qsort(from, from_count, sizeof(int), numersort);

    if(to_count < from_count) {
        sm = to;
        sm_count = to_count;
        lg = from;
        lim = to_count;
    } else {
        sm = from;
        sm_count = from_count;
        lg = to;
        lg_count = to_count;
        lim = from_count;
    }

    for(sm_index = 0, lg_index = 0; sm_index < sm_count && lg_index < lg_count; sm_index++, lg_index++) {
        if(*sm < *lg) {
            lg--;
            lg_index--;
        } else if (*sm > *lg) {
            sm--;
            sm_index--;
        } else {
            same++;
        }
        sm++;
        lg++;
    }

    return lg_count - same;
}

